//
//  ViewController.m
//  app
//
//  Created by es on 2021/12/9.
//

#import "ViewController.h"
#import "RecognizeImageCallback.h"
#import "esfaceid/ESDeviceUtils.h"
#import "MyHttpClient.h"

//屏幕宽度
#define  SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
//屏幕高度
#define  SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height

@interface ViewController ()

@end

@implementation ViewController{
    UITextView *_textView;
    
    int pickImgTarget;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    //导航栏高度
    CGFloat navHeight = self.navigationController.navigationBar.frame.size.height;
    //导航栏+状态栏高度
    CGFloat topHeight = self.navigationController.navigationBar.frame.size.height + [[UIApplication sharedApplication] statusBarFrame].size.height;
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置认证按钮布局
    button.frame = CGRectMake(10, topHeight + 50 , (SCREEN_WIDTH-20)/2-5, 50) ;
    [button setTitle:@"开始认证" forState:UIControlStateNormal];
    //设置按钮文字颜色
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor colorWithRed:239.0/255.0 green:137.0/255.0 blue:47.0/255.0 alpha:1.0]];
    //按钮圆角
    [button.layer setCornerRadius:20.0];
    //设置按钮点击事件
    [button addTarget:self action:@selector(startLivingDetect:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    UIButton * button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    
    //设置认证按钮布局
    button3.frame = CGRectMake(CGRectGetMaxX(button.frame)+5, topHeight + 50 , (SCREEN_WIDTH-20)/2-5, 50) ;
    [button3 setTitle:@"添加人脸数据" forState:UIControlStateNormal];
    //设置按钮文字颜色
    [button3 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button3 setBackgroundColor:[UIColor colorWithRed:239.0/255.0 green:137.0/255.0 blue:47.0/255.0 alpha:1.0]];
    //按钮圆角
    [button3.layer setCornerRadius:20.0];
    //设置按钮点击事件
    [button3 addTarget:self action:@selector(addFace:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button3];
    
    UIButton * button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置认证按钮布局
    button2.frame = CGRectMake(10, CGRectGetMaxY(button.frame) +20, (SCREEN_WIDTH-20)/2-5, 50) ;
    [button2 setTitle:@"初始授权" forState:UIControlStateNormal];
    //设置按钮文字颜色
    [button2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button2 setBackgroundColor:[UIColor colorWithRed:239.0/255.0 green:137.0/255.0 blue:47.0/255.0 alpha:1.0]];
    //按钮圆角
    [button2.layer setCornerRadius:20.0];
    //设置按钮点击事件
    [button2 addTarget:self action:@selector(onCreate:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    
    UIButton * button4 = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置认证按钮布局
    button4.frame = CGRectMake(CGRectGetMaxX(button.frame)+5, CGRectGetMaxY(button.frame) + 20, (SCREEN_WIDTH-20)/2, 50) ;
    [button4 setTitle:@"查询数据库" forState:UIControlStateNormal];
    //设置按钮文字颜色
    [button4 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button4 setBackgroundColor:[UIColor colorWithRed:239.0/255.0 green:137.0/255.0 blue:47.0/255.0 alpha:1.0]];
    //按钮圆角
    [button4.layer setCornerRadius:20.0];
    //设置按钮点击事件
    [button4 addTarget:self action:@selector(selectDB:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button4];
    
    UIButton * button5 = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置认证按钮布局
    button5.frame = CGRectMake(10,CGRectGetMaxY(button2.frame) + 20, (SCREEN_WIDTH-20)/2-5, 50) ;
    [button5 setTitle:@"群扫" forState:UIControlStateNormal];
    //设置按钮文字颜色
    [button5 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button5 setBackgroundColor:[UIColor colorWithRed:239.0/255.0 green:137.0/255.0 blue:47.0/255.0 alpha:1.0]];
    //按钮圆角
    [button5.layer setCornerRadius:20.0];
    //设置按钮点击事件
    [button5 addTarget:self action:@selector(imageRecognize:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button5];
    
    UIButton * btCheckCertificate = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置认证按钮布局
    btCheckCertificate.frame = CGRectMake(CGRectGetMaxX(button5.frame)+5,CGRectGetMaxY(button2.frame) + 20, (SCREEN_WIDTH-20)/2-5, 50) ;
    [btCheckCertificate setTitle:@"检查证书" forState:UIControlStateNormal];
    //设置按钮文字颜色
    [btCheckCertificate setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btCheckCertificate setBackgroundColor:[UIColor colorWithRed:239.0/255.0 green:137.0/255.0 blue:47.0/255.0 alpha:1.0]];
    //按钮圆角
    [btCheckCertificate.layer setCornerRadius:20.0];
    //设置按钮点击事件
    [btCheckCertificate addTarget:self action:@selector(checkCertificate:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btCheckCertificate];
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(button2.frame) + 50 + 20, SCREEN_WIDTH - 20, SCREEN_HEIGHT - topHeight - 150)];
    // Do any additional setup after loading the view, typically from a nib.
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(scrollView.frame.origin.x, scrollView.frame.origin.y,scrollView.frame.size.width, scrollView.frame.size.height)];
    _textView.pagingEnabled = YES;
    _textView.clipsToBounds = YES;
    _textView.editable = NO;
    
    //[self.navigationController pushViewController:_textView animated:YES];
    [self.view addSubview:_textView];
}

-(IBAction)startLivingDetect:(id)sender {
    [[EsFaceIDManager getInstance] startVerify:@"ES" ViewController:self callback:self];
}

-(IBAction)imageRecognize:(id)sender {
    pickImgTarget = 2;
    //实例化照片选择控制器
   UIImagePickerController *pickControl=[[UIImagePickerController alloc]init];
    
   //设置照片源
   [pickControl setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
   //设置协议
   [pickControl setDelegate:self];
    
   //选完图片之后回到的视图界面
   [self presentViewController:pickControl animated:YES completion:nil];
}

/**
 * 检查证书有效性
 */
-(IBAction)checkCertificate:(id)sender {
    EsFaceIDResult * checkCertificateResult = [EsFaceIDManager checkCertificate];
    [self logMsg: checkCertificateResult.errMsg];
}

-(IBAction)onCreate:(id)sender{
    EsFaceIDManager *manager = [EsFaceIDManager getInstance];
    EsFaceIDConfig *config = [EsFaceIDConfig new];
    config.threshold = 80;
    config.provider = ES_FACE_ID_PROVIDER_HAIXIN;
    config.promtWindowKeepTime = 8;
    config.promtWindowMaxNumber = 20;
    EsFaceIDResult * checkCertificateResult = [EsFaceIDManager checkCertificate];
    if(EF_SUCCESS!=[checkCertificateResult errorCode]){
        NSString* bizContext = [manager getCertificateInfo];
        [MyHttpClient getCretificate:bizContext clientCallback:^(NSString * _Nonnull resultStr) {
            if(resultStr != nullptr){
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
                NSString * certificate = [dict objectForKey:@"certificate"];
                
                EsFaceIDResult * createResult = [manager esCreateByCertificate:certificate EsFaceIDConfig:config];
                [self logMsg:createResult.errMsg];
            }
        }];
    }else{
        EsFaceIDResult * createResult = [manager esCreateByCertificate:nil EsFaceIDConfig:config];
        [self logMsg:createResult.errMsg];
    }
}

-(IBAction)addFace:(id)sender{
    pickImgTarget = 1;
    //实例化照片选择控制器
       UIImagePickerController *pickControl=[[UIImagePickerController alloc]init];
        
       //设置照片源
       [pickControl setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        
       //设置协议
       [pickControl setDelegate:self];
        
       //选完图片之后回到的视图界面
       [self presentViewController:pickControl animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    if(pickImgTarget == 1){
        NSString * dbName = @"ES";
        UIImage *image=info[@"UIImagePickerControllerOriginalImage"];
        EsFaceIDResult *result = [[EsFaceIDManager getInstance] getFaceFeature:image];
        [self dismissViewControllerAnimated:YES completion:nil];
        EsFeature* feature =  result.feature;
        feature.dbName = dbName;
        feature.persionID = [NSString stringWithUTF8String:genRandomString(10)];
        EsFaceIDResult * addResult = [[EsFaceIDManager getInstance] addFeatureToDb:feature dbName:dbName];
        //选取完图片之后关闭视图
        [self logMsg:addResult.errMsg];
    }else if(pickImgTarget == 2){
        NSString * dbName = @"ES";
        UIImage *image=info[@"UIImagePickerControllerOriginalImage"];
        RecognizeImageCallback * callback = [[RecognizeImageCallback alloc]init];
        [[EsFaceIDManager getInstance] recognitionFace:image dbName:@"ES" callback:callback];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}


/**
 * 生成随机字符串
 * @param length 字符串长度
 * @return 随机字符串指针，需在外部释放
 */
char* genRandomString(int length)
{
    int flag, i;
    char* string;
    srand((unsigned) time(NULL ));
    if ((string = (char*) malloc(length)) == NULL )
    {
        return NULL ;
    }
 
    for (i = 0; i < length - 1; i++)
    {
        flag = rand() % 3;
        switch (flag)
        {
            case 0:
                string[i] = 'A' + rand() % 26;
                break;
            case 1:
                string[i] = 'a' + rand() % 26;
                break;
            case 2:
                string[i] = '0' + rand() % 10;
                break;
            default:
                string[i] = 'x';
                break;
        }
    }
    
    string[length - 1] = '\0';
    return string;
}

-(IBAction)selectDB:(id)sender{
    EsFaceIDManager* manager = [EsFaceIDManager getInstance];
    int size = [manager getDbSize:@"ES"];
    NSLog(@"数据库中 数据的数量为:%d",size);
    [self logMsg:[NSString stringWithFormat:@"数据库中 数据的数量为:%d",size]];
    NSArray<NSString *> * personIDList= [manager listPersonIdByDbName:@"ES" limit:@"100"];
    for (NSString *personID in personIDList){
        NSLog(@"personID:%@",personID);
        [self logMsg:[NSString stringWithFormat:@"personID:%@",personID]];
    }
    
}

- (void)onError:(EsFaceIDResult *)result {
    NSString* bundleID = [ESDeviceUtils getBundleID];
    NSLog(@"onError， bundleID IS : %@", bundleID);
    [self logMsg:[NSString stringWithFormat:@"报错:%@ , bundleID = %@",result.errMsg, bundleID]];
}

- (void)onMatchResult:(NSMutableDictionary<NSString *,NSNumber *> *)result {
    NSLog(@"onMatchResult:");
}

- (void)onVerifyResult:(EsFaceIDResult *) esFaceIDResult {
    NSLog(@"onVerifyResult:");
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[esFaceIDResult toJson] options:NSJSONWritingPrettyPrinted error:nil];
    NSString * result = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [self logMsg:[NSString stringWithFormat:@"成功：%@",result]];
    UIImage *image = esFaceIDResult.faceImage;
    EsFeature* esFeeature = esFaceIDResult.feature;
    // 人脸不在库中
    static NSString* perUnregistedPersionID = @"";
    if (esFaceIDResult.errorCode == EF_FACE_UNREGISTERED) {
        if ([perUnregistedPersionID isEqual:esFeeature.persionID]) {
            [[EsFaceIDManager getInstance] addPromptBox:image title:@"识别失败" description:esFeeature.persionID promtId:esFeeature.persionID];
        }
        
        perUnregistedPersionID = esFeeature.persionID;
    } else if (esFaceIDResult.errorCode == EF_SUCCESS) { // 人脸在人脸库中
        [[EsFaceIDManager getInstance] addPromptBox:image title:@"识别成功" description: esFeeature.persionID promtId:esFeeature.persionID];
    } else {
        // 应不存在这种情况
    }
    
    //TODO: 这里暂时关闭了检测完成关闭页面
//    [[EsFaceIDManager getInstance] stopVerify];
}
- (void)logMsg:(NSString*)content {
    if (content == NULL) {
        return;
    }
    content = [NSString stringWithFormat:@"%@ \n", content];
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:content];
        [string addAttribute:NSForegroundColorAttributeName
                       value:[UIColor blackColor]
                       range:NSMakeRange(0, content.length)];
        
        [string addAttribute:NSFontAttributeName
                       value:[UIFont systemFontOfSize:15]
                       range:NSMakeRange(0 , content.length)];
        NSMutableAttributedString* tvStr = [[NSMutableAttributedString alloc] initWithAttributedString:self->_textView.attributedText];
        
        [tvStr appendAttributedString:string];
        [self->_textView setAttributedText:tvStr];
    });
}
@end
